package com.runtime;

import cn.hutool.core.io.IoUtil;
import lombok.extern.slf4j.Slf4j;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.concurrent.TimeUnit;

/**
 * @Author: liuli31
 * @Description:
 * @Date: 2023/12/12 14:50
 * @Version: 1.0
 */
@Slf4j
public class RuntimeUtil {

    /**
     * 执行命令并返回执行结果
     *
     * @param command 命令字符串
     * @param dir 执行路径
     * @return 执行结果，如果执行成功返回 true，否则返回 false
     * @throws Exception 如果执行过程中发生异常
     */

    public static Boolean exec(String command,String dir){
        try {
            File file = new File(dir);
            if(!file.exists()){
                file.mkdirs();
            }
            Runtime runtime = Runtime.getRuntime();
            Process process = runtime.exec(command, new String[]{}, file);
            BufferedOutputStream outputStream = (BufferedOutputStream)process.getOutputStream();
            InputStream inputStream = process.getInputStream();
            InputStream errorStream = process.getErrorStream();
            process.waitFor(1, TimeUnit.MINUTES);
            IoUtil.readUtf8(inputStream);
            String msg = IoUtil.readUtf8(errorStream);
            log.info("命令:{},执行路径:{},结果:{}",command,dir,msg);

            process.destroy();
            process.destroyForcibly();
            IoUtil.close(errorStream);
            IoUtil.close(inputStream);
            IoUtil.close(outputStream);
        } catch (Exception e) {
            log.error("命令:{},执行路径:{},结果:{}",command,dir,e.getMessage(),e);
          return  false;
        }
        return true;
    }
}
